﻿using System.Windows.Media.Animation;
using System.Windows.Controls;
using System;
using System.Windows;

namespace System.Windows {
	public static class ControlFade {
		//public static void Show(this FrameworkElement fe) {
		//  var sb = new Storyboard();
		//  InitializeFade(0, 1, sb, fe);
		//  fe.Visibility = Visibility.Visible;
		//  sb.Begin();
		//}

		//public static void Hide(this FrameworkElement fe) {
		//  var sb = new Storyboard();
		//  InitializeFade(1, 0, sb, fe);
		//  sb.Completed += (s, e) => fe.Visibility = Visibility.Collapsed;
		//  sb.Begin();
		//}

		//private static readonly TimeSpan FadeDuration = TimeSpan.FromSeconds(0.5D);
		//private static void InitializeFade(double from, double to, Storyboard sb, FrameworkElement target) {
		//  var opacityAnimiation = new DoubleAnimation();
		//  opacityAnimiation.From = from;
		//  opacityAnimiation.To = to;
		//  opacityAnimiation.Duration = FadeDuration;
		//  sb.Children.Add(opacityAnimiation);
		//  Storyboard.SetTarget(opacityAnimiation, target);
		//  Storyboard.SetTargetProperty(opacityAnimiation, new PropertyPath(FrameworkElement.OpacityProperty));
		//}
	}
}

namespace TheVerge.Phone.Controls {
	public class FadeGrid : Grid {

		private Storyboard ShowSB = new Storyboard();
		private Storyboard HideSB = new Storyboard();
		private static readonly TimeSpan FadeDuration = TimeSpan.FromSeconds(0.25D);

		public FadeGrid() : base() {
			InitializeFade(0, 1, ShowSB, this);			
			InitializeFade(1, 0, HideSB, this);
			HideSB.Completed += (s, e) => Visibility = Visibility.Collapsed;
		}

		private static void InitializeFade(double from, double to, Storyboard sb, FrameworkElement target) {
			var opacityAnimiation = new DoubleAnimation();
			opacityAnimiation.From = from;
			opacityAnimiation.To = to;
			opacityAnimiation.Duration = FadeDuration;
			sb.Children.Add(opacityAnimiation);
			Storyboard.SetTarget(opacityAnimiation, target);
			Storyboard.SetTargetProperty(opacityAnimiation, new PropertyPath(FrameworkElement.OpacityProperty));
		}

		public void Hide() {
			HideSB.Begin();
		}

		public void Show() {
			Visibility = Visibility.Visible;
			Opacity = 0.01;
			ShowSB.Begin();
		}

        public void ShowQuick()
        {
            Visibility = Visibility.Visible;
            Opacity = 1;
        }
	}
}
